using Microsoft.EntityFrameworkCore;
using UniversalAdmin.Domain.Entities;
using UniversalAdmin.Domain.Repositories;
using UniversalAdmin.Infrastructure.Data.Contexts;

namespace UniversalAdmin.Infrastructure.Repositories;

public class DocumentRepository : Repository<Document>, IDocumentRepository
{
    public DocumentRepository(ApplicationDbContext context) : base(context)
    {
    }

    public async Task<(IEnumerable<Document> Documents, int TotalCount)> GetPagedAsync(int page, int pageSize, string? keyword = null, DocumentStatus? status = null, Guid? userId = null)
    {
        var query = _context.Documents
            .Include(d => d.DocumentPermissions)
            .AsQueryable();

        if (!string.IsNullOrEmpty(keyword))
        {
            query = query.Where(d =>
                d.Title.Contains(keyword) ||
                d.FileName.Contains(keyword));
        }

        if (status.HasValue)
        {
            query = query.Where(d => d.Status == status.Value);
        }

        if (userId.HasValue)
        {
            query = query.Where(d =>
                d.CreatedBy == userId.ToString() ||
                d.DocumentPermissions.Any(p => p.UserId == userId));
        }

        var totalCount = await query.CountAsync();
        var documents = await query
            .OrderByDescending(d => d.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();

        return (documents, totalCount);
    }

    public async Task<IEnumerable<Document>> GetByUserIdAsync(Guid userId, int page, int pageSize)
    {
        return await _context.Documents
            .Include(d => d.DocumentPermissions)
            .Where(d =>
                d.CreatedBy == userId.ToString() ||
                d.DocumentPermissions.Any(p => p.UserId == userId))
            .OrderByDescending(d => d.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    public async Task<IEnumerable<Document>> GetByStatusAsync(DocumentStatus status, int page, int pageSize)
    {
        return await _context.Documents
            .Where(d => d.Status == status)
            .OrderByDescending(d => d.CreatedAt)
            .Skip((page - 1) * pageSize)
            .Take(pageSize)
            .ToListAsync();
    }

    public async Task<bool> ExistsByFilePathAsync(string filePath)
    {
        return await _context.Documents.AnyAsync(d => d.FilePath == filePath);
    }

    public async Task<IEnumerable<Document>> GetRelatedDocumentsAsync(Guid documentId, int topCount = 5)
    {
        // 这里简化实现，实际项目中可能需要基于内容相似度进行推荐
        var document = await _context.Documents.FindAsync(documentId);
        if (document == null)
            return Enumerable.Empty<Document>();

        return await _context.Documents
            .Where(d => d.Id != documentId && d.Status == DocumentStatus.Processed)
            .OrderByDescending(d => d.CreatedAt)
            .Take(topCount)
            .ToListAsync();
    }
}